package com.mstore.interceptor;

import java.lang.reflect.Method;

import org.apache.struts2.ServletActionContext;

import com.mstore.pojo.Account;
import com.mstore.pojo.User;
import com.mstore.service.AuthorityService;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * 用于拦截请求判断是否拥有权限的拦截器
 * 
 */
@SuppressWarnings("serial")
public class AuthorityInterceptor implements Interceptor {

	private AuthorityService authorityService;

	@Override
	public void destroy() {
	}

	@Override
	public void init() {
	}

	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		String methodName = actionInvocation.getProxy().getMethod();
		Method currentMethod = actionInvocation.getAction().getClass()
				.getMethod(methodName);

		// 特殊的action访问不拦截
		if (currentMethod.isAnnotationPresent(Authority.class)) {
			// 获取权限校验的注解
			Authority authority = currentMethod.getAnnotation(Authority.class);
			// 获取当前请求的注解的actionName
			String actionName = authority.actionName();
			// 获取当前请求需要的权限
			String privilege = authority.privilege();

			// 验证码生成、企业注册验证不拦截
			if ("maccount".equals(actionName) && "pass".equals(privilege)) {
				return actionInvocation.invoke();
			}
			else if ("muser".equals(actionName) && "pass".equals(privilege)) {
				return actionInvocation.invoke();
			}
		}

		// 1、判断客户是否登陆
		// 从session获取当前客户信息
		Account account = (Account) ServletActionContext.getRequest()
				.getSession().getAttribute("account");
		User user = (User) ServletActionContext.getRequest().getSession()
				.getAttribute("user");
		if (account == null) {
			if (user == null) {
				return "logout";
			}
		}

		// 2、进行权限控制判断

		// 如果该请求方法是需要进行验证的则需执行以下逻辑
		// if (currentMethod.isAnnotationPresent(Authority.class)) {
		// // 获取权限校验的注解
		// Authority authority = currentMethod.getAnnotation(Authority.class);
		// // 获取当前请求的注解的actionName
		// String actionName = authority.actionName();
		// // 获取当前请求需要的权限
		// String privilege = authority.privilege();
		//
		// boolean haveAuthority = false;
		// BAuthority b_authority = new BAuthority();
		// b_authority.setEa_id(account.getId());
		// List<BAuthority> authorities = authorityService
		// .haveAllAuthority(b_authority);
		// for (BAuthority bAuthority : authorities) {
		// if (actionName.equals(bAuthority.getActionName())
		// && privilege.equals(bAuthority.getPrivilege())) {
		// haveAuthority = true;
		// break;
		// }
		// }
		//
		// if (haveAuthority) {
		// return actionInvocation.invoke();
		// } else {
		// return "noAuthority";
		// }
		//
		// }

		return actionInvocation.invoke();
	}

	public AuthorityService getAuthorityService() {
		return authorityService;
	}

	public void setAuthorityService(AuthorityService authorityService) {
		this.authorityService = authorityService;
	}

}
